package cn.wolfcode.mq.listener;

import cn.wolfcode.mq.MQConstant;
import cn.wolfcode.mq.OrderMQResult;
import cn.wolfcode.mq.OrderMessage;
import cn.wolfcode.service.IOrderInfoService;
import cn.wolfcode.web.msg.SeckillCodeMsg;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

@Component
@RocketMQMessageListener(
        consumerGroup = "OrderMessageListener",
        topic = MQConstant.ORDER_PEDDING_TOPIC
)
public class OrderMessageListener implements RocketMQListener<OrderMessage> {

    @Autowired
    private IOrderInfoService orderInfoService;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public void onMessage(OrderMessage orderMessage) {
        Integer time = orderMessage.getTime();
        String token = orderMessage.getToken();
        Long seckillId = orderMessage.getSeckillId();
        Long phone = orderMessage.getUserPhone();
        OrderMQResult result = new OrderMQResult();
        result.setSeckillId(seckillId);
        result.setTime(time);
        result.setToken(token);
        String tag = "";
        // 秒杀业务逻辑
        try {
            String orderNo = orderInfoService.doSeckill(time, seckillId, phone);
            result.setOrderNo(orderNo);
            tag = MQConstant.ORDER_RESULT_SUCCESS_TAG;
            // 发送延时消息
            rocketMQTemplate.syncSend(MQConstant.ORDER_PAY_TIMEOUT_TOPIC, MessageBuilder.withPayload(result).build(),10000,MQConstant.ORDER_PAY_TIMEOUT_DELAY_LEVEL);
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(SeckillCodeMsg.SECKILL_ERROR.getCode());
            result.setMsg(SeckillCodeMsg.SECKILL_ERROR.getMsg());
            tag = MQConstant.ORDER_RESULT_FAIL_TAG;
        }
        // 发送消息
        rocketMQTemplate.sendOneWay(MQConstant.ORDER_RESULT_TOPIC + ":" + tag , result);
    }
}
